package com.share.two.a_proxy.b_cglib;

import java.lang.reflect.Method;

import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;


public class MyBeanFactory {
	
	
	public static UserServiceImpl creatBean(){
		final UserServiceImpl userService = new UserServiceImpl();
		final MyAspect myAspect = new MyAspect();

		//底层是创建目标子类：proxy
		Enhancer enhancer = new Enhancer();
		enhancer.setSuperclass(userService.getClass());
		/* 3.3 设置回调函数 , MethodInterceptor接口 等效 jdk InvocationHandler接口
		 * 	intercept() 等效 jdk  invoke()
		 * 		参数1、参数2、参数3：以invoke一样
		 * 		参数4：methodProxy 方法的代理
		 * 		
		 * 
		 */
		enhancer.setCallback(new MethodInterceptor() {

			@Override
			public Object intercept(Object proxy, Method method, Object[] args,
					MethodProxy methodProxy) throws Throwable {

				myAspect.before();
				Object obj = method.invoke(userService, args);//执行目标方法
				//Object invokeSuper = methodProxy.invokeSuper(proxy, args);
				myAspect.after();

				return obj;
			}
		});

		UserServiceImpl proxyService = null;
		proxyService = (UserServiceImpl) enhancer.create();

		return proxyService;

	}

}
